require('./style.less');
define( [
  'require',
  'jquery',
  'constants',
  'transit',
  'artTemplate',
  'api',
], function( require, $, c, tras, at ) {
  'use strict';

  var apis = require( 'api' );

  var pl = $( '#public_list' );
  var pfl = $( '.platf_pblc_choose' );

  var definedCallback = {};
  var platform_pt = 'weixin';
  var public_json = {};
  var autoRefresh = true;

  var utils = {
    autoRefreshAccount: function( data, l ) {
      if ( autoRefresh && data ) {
        autoRefresh && $( '.public_choose', pfl ).removeClass( 'hide' );
        $( '.account_null', pfl ).addClass( 'hide' );
        $( '.account_info', pfl ).html( at( 'user_default_account_html', data ) );
      }
      $( '.spinner', pfl ).addClass( 'hide' );
      if ( typeof definedCallback.sure === 'function' ) {
        definedCallback.sure.call( this, data, platform_pt, l || false );
      }
    },
    setPlatformActive: function( platform ) {
      var $active = $( '[data-platform="' + ( platform || 'weixin' ) + '"]', pfl );
      $active.addClass( 'active' ).siblings().removeClass( 'active' );
      $( '.public_platform', pfl ).transit( {
        x: -$active.position().left
      }, 150, 'ease', function() {
        $( this ).parent().trigger( 'mouseleave' );
      } );
    }
  }

  var ptfmAccount = {
    'weixin': {
      dftAccount: null
    },
    'sina': {
      dftAccount: null
    },
    'toutiao': {
      dftAccount: null
    },
  }
  var platformPublic = {
    weixin: {
      init: function( data ) {
        $( '.acount_type', pfl ).text( '公众号' );
        if ( !data ) return data;
        data.face_img_url = data.image || ( c.resPath + '/images/default_face.png' );
        return data;
      },
      platform: 'mp.weixin.qq.com',
      text: '您还没有绑定授权公众号',
      href: '/my_account',
      modal_title: '选择公众号'
    },
    sina: {
      init: function( data ) {
        $( '.acount_type', pfl ).text( '微博号' );
        if ( !data ) return data;
        data.face_img_url = data.profile_image_url || c.resPath + '/images/default_face.png';
        data.user_name = data.screen_name || '';
        return data;
      },
      platform: 'sina.com',
      text: '您还没有绑定授权微博号',
      href: '/my_account?platform=sina',
      modal_title: '选择微博号'
    },
    toutiao: {
      init: function( data ) {
        $( '.acount_type', pfl ).text( '头条号' );
        if ( !data ) return data;
        data.face_img_url = data.avatar_url || c.resPath + '/images/default_face.png';
        data.user_name = data.screen_name || '';
        return data;
      },
      platform: 'toutiao.com',
      text: '您还没有绑定授权头条号',
      href: '/my_account?platform=toutiao',
      modal_title: '选择头条号'
    },
    getDefualtAccount: function( platform, publicApid ) {
      var that = this;
      if ( autoRefresh ) {
        $( '.spinner', pfl ).removeClass( 'hide' );
        $( '.public_choose', pfl ).addClass( 'hide' ).find( '.account_info' ).empty();
      }

      if ( platform ) {
        $( '.modal-title', pl ).html( that[ platform ].modal_title );
      }

      return $.ajax( {
        url: apis.THIRD_PARTY.PLATFORM_ACOUNT,
        type: 'post',
        data: {
          platform: that[ platform ] && that[ platform ].platform,
          account_id: publicApid || '',
        },
        success: function( data ) {
          data = typeof data === 'string' ? $.parseJSON( data ) : data;
          if ( data.ret === 0 ) {
            platform_pt = platform = platformMap[ data.data.platform ];
            utils.setPlatformActive( platform );

            if ( data.data.user_account ) {
              autoRefresh && $( '.public_choose', pfl ).removeClass( 'hide' );
              $( '.account_null', pfl ).addClass( 'hide' );
              $( '.account_info', pfl ).data( data.data );
              ptfmAccount[ platform ].dftAccount = data.data.user_account;
            } else {
              var pt = that[ platform ];
              var _hf = '';
              if ( pfl.data( 'session' ) == 'oauth' ) {
                _hf = '<a href="#" onclick="javascript:void(0);$(\'#register-guide\').modal(\'show\');">账号设置</a>'
              } else {
                _hf = '<a href="' + pt.href + '">账号设置</a>'
              }
              $( '.public_choose', pfl ).addClass( 'hide' );
              $( '.account_null', pfl ).removeClass( 'hide' ).html( '<span class="iconfont icon-warning"></span><p class="title">' + pt.text + '</p><p class="spa_gray">请前往中' + _hf + '绑定</p>' );
            }
            utils.autoRefreshAccount( that[ platform ].init( data.data.user_account ) );
          }
        }
      } );
    }
  }
  var platformMap = {};

  for ( var i in platformPublic ) {
    if ( typeof platformPublic[ i ] === 'object' ) {
      platformMap[ platformPublic[ i ].platform ] = i;
    }
  }
  /**
   * platform 要显示的平台数组或字符串
   * defaultPlatform    默认显示的平台
   * callback 平台或公众号改变的回调
   * autoRefresh 是否自动刷新选择后的dom
   */
  definedCallback.init = function( obj ) {
    var defaultPlatform = obj.defaultPlatform || 'weixin';
    platform_pt = defaultPlatform;
    // 默认自动刷新
    autoRefresh = obj.autoRefresh === undefined ? true : obj.autoRefresh;

    if ( !obj.platform ) {
      obj.defaultPlatform = obj.platform = 'weixin';
    }

    obj.platform = obj.platform instanceof Array ? obj.platform : [ obj.platform ];

    for ( var i in obj.platform ) {
      $( '[data-platform="' + obj.platform[ i ] + '"]', pfl ).removeClass( 'hide' );
    }

    obj.platform.length > 1 && $( '.platform_list', pfl ).addClass( 'more_platform' );

    utils.setPlatformActive();

    platformPublic.getDefualtAccount( obj.defaultPlatform, obj.defaultPublic );
    typeof obj.callback === 'function' && ( definedCallback.sure = obj.callback );

  };

  pl.on( 'show.bs.modal', function() {
    var pt_s = $( '.public_platform > .platform_item.active' ).data( 'pt' );
    var len = pl.find( '.account_detail.' + platform_pt + '>.detail_sub' ).length;
    pl.find( '.account_detail' ).addClass( 'hide' ).removeClass( 'show' );
    if ( len > 1 ) {
      pl.find( '.account_detail.' + platform_pt ).addClass( 'show' ).removeClass( 'hide' );
      return;
    }
    pl.find( '.account_detail' ).addClass( 'hide' ).removeClass( 'show' );
    pl.find( '.spinner' ).addClass( 'show' ).removeClass( 'hide' );
    public_list();
  } ).on( 'click', '.account_detail .detail_sub', function() {
    $( this ).addClass( "cover" ).siblings().removeClass( "cover" );
  } ).on( 'click', '.modal-footer .sure', function() {
    $( this ).addClass( 'disabled' ).prop( 'disabled', true );
    pl.modal( 'hide' );
    var i = pl.find( '.account_detail.' + platform_pt + ' > .detail_sub.cover' ).index();
    var dftAccount = public_json[ platform_pt ][ i ];
    ptfmAccount[ platform_pt ].dftAccount = dftAccount;
    utils.autoRefreshAccount( platformPublic[ platform_pt ].init( dftAccount ), true );
    if ( platform_pt === 'weixin' ) {
      $.post( 'save_gzh/index', {
        app_id: dftAccount.app_id,
        done: 'sending'
      } );
    }
  } ).on( 'hide.bs.modal', function() {
    pl.find( '.sure' ).removeClass( 'disabled' ).prop( 'disabled', false );
    pl.removeAttr( 'data-imageid' );
  } );

  function public_list() {
    var html = '';
    if ( platform_pt == 'weixin' ) {
      $.post( apis.SEND_PREVIEW.GET_SEND_PREVIEW, {}, function( data ) {
        var json = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( json.length == 0 ) {
          html = '<div class="public_null"><p>您还没有绑定授权公众号</p><p>请前往<a href="/my_account">账号设置</a>中绑定</p></div>'
        } else {
          public_json.weixin = json;
          if ( !autoRefresh ) {
            html += '<div class="detail_sub cover"><p>全部公众号</p></div>';
          }
          for ( var i in json ) {
            if ( i == 0 && autoRefresh ) {
              html += '<div class="detail_sub cover" data-info="' + json[ i ].verify_type_info + '" data-appid ="' + json[ i ].app_id + '" data-login="' + json[ i ].login_account + '">';
            } else {
              html += '<div class="detail_sub" data-info="' + json[ i ].verify_type_info + '" data-appid ="' + json[ i ].app_id + '" data-login="' + json[ i ].login_account + '">';
            }
            html += '<img src="' + ( json[ i ].image || c.resPath + '/images/default_face.png' ) + '" class="pub_img"><div class="sub_text"><p class="pub_name">' + json[ i ].user_name + '</p><p class="pub_type"><span class="iconfont icon-dingyuehao"></span><span>&nbsp;订阅号</span></p></div></div>';
          }
          if ( !autoRefresh ) {
            public_json.weixin.unshift( {
              include: 'all'
            } );
          }
        }
        pl.find( '.account_detail.' + platform_pt ).empty().append( html ).addClass( 'show' ).removeClass( 'hide' );
        pl.find( '.spinner' ).addClass( 'hide' ).removeClass( 'show' );
      } );
    } else if ( platform_pt == 'sina' ) {
      $.post( apis.THIRD_PARTY.SINA_ACOUNT_LIST, {}, function( data ) {
        var json = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( json.length == 0 ) {
          html = '<div class="public_null"><p>您还没有绑定授权公众号</p><p>请前往<a href="/my_account?platform=sina">账号设置</a>中绑定</p></div>'
        } else {
          public_json.sina = json.data;
          if ( !autoRefresh ) {
            html += '<div class="detail_sub cover"><p>全部微博号</p></div>'
          }
          for ( i in json.data ) {
            if ( i == 0 && autoRefresh ) {
              html += '<div class="detail_sub cover" data-info="' + json.data[ i ].verified + '" data-appid ="' + json.data[ i ].uid + '">';
            } else {
              html += '<div class="detail_sub" data-info="' + json.data[ i ].verified + '" data-appid ="' + json.data[ i ].uid + '">';
            }
            html += '<img src="' + ( json.data[ i ].profile_image_url || c.resPath + '/images/default_face.png' ) + '" class="pub_img"><div class="sub_text"><p class="pub_name">' + json.data[ i ].screen_name + '</p></div></div>';
          }
          if ( !autoRefresh ) {
            public_json.sina.unshift( {
              include: 'all'
            } );
          }
        }
        pl.find( '.account_detail.' + platform_pt ).empty().append( html ).addClass( 'show' ).removeClass( 'hide' );
        pl.find( '.spinner' ).addClass( 'hide' ).removeClass( 'show' );
      } )
    } else if ( platform_pt == 'toutiao' ) {
      $.ajax( {
        type: 'post',
        url: apis.THIRD_PARTY.TOUTIAO_ACOUNT_LIST,
        data: {},
        success: function( data ) {
          var json = typeof data === 'string' ? $.parseJSON( data ) : data;
          if ( json.length == 0 ) {
            html = '<div class="public_null"><p>您还没有绑定授权公众号</p><p>请前往<a href="/my_account?platform=toutiao">账号设置</a>中绑定</p></div>'
          } else {
            public_json.toutiao = json.data;
            if ( !autoRefresh ) {
              html += '<div class="detail_sub cover"><p>全部头条号</p></div>'
            }
            for ( i in json.data ) {
              if ( i == 0 && autoRefresh ) {
                html += '<div class="detail_sub cover" data-info="' + json.data[ i ].is_cancel + '" data-appid ="' + json.data[ i ].uid + '">';
              } else {
                html += '<div class="detail_sub" data-info="' + json.data[ i ].is_cancel + '" data-appid ="' + json.data[ i ].uid + '">';
              }
              html += '<img src="' + ( json.data[ i ].avatar_url || c.resPath + '/images/default_face.png' ) + '" class="pub_img"><div class="sub_text"><p class="pub_name">' + json.data[ i ].screen_name + '</p></div></div>';
            }
            if ( !autoRefresh ) {
              public_json.toutiao.unshift( {
                include: 'all'
              } );
            }
          }
          pl.find( '.account_detail.' + platform_pt ).empty().append( html ).addClass( 'show' ).removeClass( 'hide' );
          pl.find( '.spinner' ).addClass( 'hide' ).removeClass( 'show' );
        }
      } )
    }
  };

  pfl.on( {
    mouseleave: function() {
      $( this ).removeClass( 'active' );
    },
    mouseenter: function() {
      $( this ).addClass( 'active' );
    }
  }, '.platform_list.more_platform' ).on( 'click', '.platform_item', function() {
    var $t = $( this );
    if ( $t.hasClass( 'active' ) ) {
      return;
    }
    $t.addClass( 'active' ).siblings().removeClass( 'active' );
    var platform = platform_pt = $t.data( 'platform' );
    var dftAccount = ptfmAccount[ platform ].dftAccount;
    $( '.account_null', pfl ).addClass( 'hide' );
    utils.setPlatformActive( platform );
    if ( !dftAccount ) {
      platformPublic.getDefualtAccount( platform );
    } else {
      utils.autoRefreshAccount( platformPublic[ platform ].init( dftAccount ) );
    }

    $.isFunction( definedCallback.platform ) && definedCallback.platform( $t.data( 'pt' ) );

  } );

  return definedCallback;
} );
